package client.comm.baoding.ui.vm

import android.app.Application
import android.os.Looper
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.baoding.MyApp
import client.comm.baoding.api.bean.CheckPayBean
import client.comm.baoding.api.bean.PayUrlBean
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.network.data.Ret
import client.comm.commlib.utils.StoreUtil
import client.comm.baoding.api.bean.ShopingBean
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.baoding.api.bean.UserInfo
import client.comm.commlib.out_time
import client.comm.commlib.toast.toast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.json.JSONArray
import org.json.JSONObject
import retrofit2.Response

class ConfirmOrderModel(app: Application) : MiddleVm(app) {

    val isShowing = MutableLiveData<Boolean>()

    /**
     * 1余额支付
     * 2礼金券 -分享积分
     * 3支付宝支付
     * 4体验券
     */
    val payType = MutableLiveData<Int>(0)
    val payTypeTxt = MutableLiveData<String>("请选择支付方式")
    val isSy = MutableLiveData<Boolean>(false)
    val commitRet = MutableLiveData<JsonResult<PayUrlBean>>()
    val aliPayRet = MutableLiveData<JsonResult<Ret>>()
    val userRet = MutableLiveData<JsonResult<UserInfo>>()
    val checkOrderPayCall = MutableLiveData<JsonResult<CheckPayBean>>()

    fun userInfo() {
        hold({
            server.userinfo().apply {
                body()?.let {
                    if (it.isSuccess) {
                        StoreUtil.saveBean(getApplication(), it.data!!)
                    }
                }
            }
        }, success = {
            userRet.value = it
        })
    }

    fun commitOrderByPayPwdValid(
        it: String,
        list: ArrayList<ShopingBean>,
        address_id: String,
        user_coupons_id: String?
    ) {
//        var t_message = ""
        isShowing.value = true
        viewModelScope.launch {
            flow {
                var emm: Response<JsonResult<Ret>>? = null
                out_time {
                    val ret = server.validatePayPwd(it)
                    emm = ret
                }

                emit(emm)
            }.map {
                var emm: JsonResult<PayUrlBean>? = null

                it?.body()?.let {
                    if (it.isSuccess) {
                        out_time {
                            val obj = JSONObject()
                            obj.put("address_id", address_id)
                            obj.put("pay_type", payType.value!!) //1现金 ，2现金和提现金
                            obj.put("user_coupons_id", user_coupons_id) //1现金 ，2现金和提现金
                            val jsonList = JSONArray()
                            for (i in list) {
                                val ttt = JSONObject()
                                ttt.put("goods_id", i.goods_id)
                                ttt.put("store_id", i.store_id)
                                ttt.put("num", i.num)
                                ttt.put("shopping_id", i.shopping_id)
                                jsonList.put(ttt)
                            }
                            obj.put("goods_list", jsonList)
                            val body = RequestBody.create(
                                "application/json;charset=UTF-8".toMediaTypeOrNull(),
                                obj.toString()
                            )
                            val ret = server.goods_buy(body)
                            emm = ret.body()
                        }
                    } else {
                        emm = JsonResult<PayUrlBean>().apply {
                            code = it.code
                            message = it.message
                        }

                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion {
                isShowing.value = false
            }.catch { cause ->
//                isShowing.value = false
                if (cause != null) {

//                        Toast.makeText(getApplication(), cause.message, Toast.LENGTH_SHORT).show()

//                        toast(t_message)
                        toast("网络错误")

//                        cause.message?.let { it1 -> Log.i(MyApp.TAG, it1) }
//
                }
            }.collectLatest {
                commitRet.value = it
            }


        }


        //------------------------------------

//        hold({
//            val obj = JSONObject()
//            obj.put("address_id", address_id)
//            obj.put("pay_type", payType.value!!) //1现金 ，2现金和提现金
//            obj.put("user_coupons_id", user_coupons_id) //1现金 ，2现金和提现金
//            val jsonList = JSONArray()
//            for (i in list) {
//                val ttt = JSONObject()
//                ttt.put("goods_id", i.goods_id)
//                ttt.put("store_id", i.store_id)
//                ttt.put("num", i.num)
//                ttt.put("shopping_id", i.shopping_id)
//                jsonList.put(ttt)
//            }
//            obj.put("goods_list", jsonList)
//            val body = RequestBody.create(
//                "application/json;charset=UTF-8".toMediaTypeOrNull(),
//                obj.toString()
//            )
//            server.goods_buy(body)
//        }, {
//            isShowing.value = true
//        }, {
//            commitRet.value = it
//        }, complete = {
//            isShowing.value = false
//        })


    }

    fun commitOrder(list: ArrayList<ShopingBean>, address_id: String, user_coupons_id: String?) {
        hold({
            val obj = JSONObject()
            obj.put("address_id", address_id)
            obj.put("pay_type", payType.value!!) //1现金 ，2现金和提现金
            obj.put("user_coupons_id", user_coupons_id) //1现金 ，2现金和提现金
            val jsonList = JSONArray()
            for (i in list) {
                val ttt = JSONObject()
                ttt.put("goods_id", i.goods_id)
                ttt.put("store_id", i.store_id)
                ttt.put("num", i.num)
                ttt.put("shopping_id", i.shopping_id)
                jsonList.put(ttt)
            }
            obj.put("goods_list", jsonList)
            val body = RequestBody.create(
                "application/json;charset=UTF-8".toMediaTypeOrNull(),
                obj.toString()
            )
            server.goods_buy(body)
        }, {
            isShowing.value = true
        }, {
            commitRet.value = it
        }, complete = {
            isShowing.value = false
        })

    }


    fun commitOrderAliPay(
        list: ArrayList<ShopingBean>,
        address_id: String,
        user_coupons_id: String?
    ) {
        hold({
            val obj = JSONObject()
            obj.put("address_id", address_id)
            obj.put("pay_type", payType.value!!) //1现金 ，2现金和提现金
            obj.put("user_coupons_id", user_coupons_id) //1现金 ，2现金和提现金
            val jsonList = JSONArray()
            for (i in list) {
                val ttt = JSONObject()
                ttt.put("goods_id", i.goods_id)
                ttt.put("store_id", i.store_id)
                ttt.put("num", i.num)
                ttt.put("shopping_id", i.shopping_id)
                jsonList.put(ttt)
            }
            obj.put("goods_list", jsonList)
            val body = RequestBody.create(
                "application/json;charset=UTF-8".toMediaTypeOrNull(),
                obj.toString()
            )
            server.goods_buy(body)
        }, {
            isShowing.value = true
        }, {
//            aliPayRet.value = it
        }, complete = {
            isShowing.value = false
        })

    }

    fun check_order_pay(trade_no: String) {
        isShowing.value = true
        hold({
            server.check_order_pay(trade_no)
        }, success = {
            checkOrderPayCall.value = it
        }, complete = {
            isShowing.value = false
        })
    }


//    fun alipayVerify(order_sn: String, type: String) {
//        hold({
//            server.alipay_post(order_sn, type)
//        }, {
//            isShowing.value = true
//        }, {
//            aliPayRet.value = it
//        }, complete = {
//            isShowing.value = false
//        })
//    }

}